/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package FileComponent;

import Bean.File.FileBean;
import DB.DBConnection;
import java.sql.*;
import java.io.*;
import java.sql.ResultSet;
import java.util.Iterator;
import javax.servlet.ServletContext;
import org.apache.commons.fileupload.FileItem;

/**
 *
 * @author DIT-0958372
 */
public class FileLogic {

    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    private FileBean f = null;

    protected boolean processUpload(Iterator it, ServletContext sc, String savePath) {
        boolean isDone = false;
        try {
            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();
                if (item.isFormField()) {
                    System.out.println("Form Name:" + item.getFieldName()
                            + ",Data:" + item.getString());
                } else {
                    if (item.getName() != null && !item.getName().equals("")) {

                        File tempFile = new File(item.getName());
                        String finalPath = sc.getRealPath("/") + savePath;
                        File file = new File(finalPath,
                                tempFile.getName());

                        item.write(file);
                        f = new FileBean();

                        //fail to get the type for some files
                        f.setFileType(item.getContentType());
                        f.setFileName(item.getName());//done
                        f.setPath(finalPath);//done
                        f.setSize(item.getSize());//done
                        //Pending function
                        f.setCategory("Not Defined");
                        //Link to the user
                        f.setUploader("user");//user name here

//                      this method is to create the new entry for the file uploaded
                        isDone = updateFileDB(f);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isDone;
    }

    protected boolean updateFileDB(FileBean f) {
        boolean isDone = false;
        String sql = "";

        try {
            //get DB connection
            DBConnection db = new DBConnection();
            conn = db.getConnection();

            sql = "call createNewFile(?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, f.getFileName());
            pstmt.setString(2, f.getFileType());
            pstmt.setString(3, f.getCategory());
            pstmt.setInt(4, (int) f.getSize());
            pstmt.setString(5, f.getPath());
            pstmt.setString(6, f.getUploader());

            int check = pstmt.executeUpdate();

            if (check == 1) {
                isDone = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return isDone;
    }

    protected FileBean retrieveFileInfo(String condition, String fileIndex) {
        // boolean isDone = false;
        String sql = "call retrieveFileInfo(?,?)";

        try {
            //get DB connection
            DBConnection db = new DBConnection();
            conn = db.getConnection();
            pstmt = conn.prepareStatement(sql);

            //pass in the condition
            pstmt.setString(1, condition);
            
            //prepare this for the future search function
            if (condition.equals("retrieveAll")) {
                pstmt.setString(2, "null");
            } else if (condition.equals("selectIndex")) {
                pstmt.setString(2, fileIndex);
            } else if (condition.equals("search")) {
            }//condition reserved for future search function

            rs = pstmt.executeQuery();

            while (rs.next()) {
                f = new FileBean();
                f.setFileName(rs.getString("fileName"));
                f.setFileType(rs.getString("fileType"));
                f.setCategory(rs.getString("category"));
                f.setSize(rs.getInt("size"));
                f.setUploader(rs.getString("uploader"));
            }

            //if the while loop is successfully executed, the fileBean will not be null
            // if (f != null) {
            //isDone = true;
            //}
        } catch (Exception e) {
            e.printStackTrace();
            f = null;
        } finally {
            this.close();
        }
        return f;
    }

    protected void close() {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (pstmt != null) {
                pstmt.close();
                pstmt = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}
